package com.sznaner.tool.util;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInstaller;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;



//https://www.jianshu.com/p/1860fd278b16


public class ApkInstallUtil {

    public static Handler handler = new Handler();

    //子线程静默安装app(需要系统app权限)(https://blog.csdn.net/qhs1573/article/details/81030567)
    public static void installApkAuto_async(final String apkPath, final InstallApkAutoCallBack callBack){
        new Thread(new Runnable() {
            @Override
            public void run() {
                //耗时操作子线程中进行
                final boolean result = installApkAuto(apkPath);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI
                        if(callBack != null){
                            callBack.finishCallBack(result);
                        }
                    }});
            }
        }).start();

    }


    //静默安装apk
    public static boolean installApkAuto(String apkPath) {
        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();

        String packageName = AppUtil.getPackageName();
        try {
            process = new ProcessBuilder("pm", "install","-i",packageName, "-r", apkPath).start();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {

        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {

            }
            if (process != null) {
                process.destroy();
            }
        }

        //如果含有“success”单词则认为安装成功
        boolean result = successMsg.toString().equalsIgnoreCase("success");
        if(result){
            Log.d("apk静默安装成功",successMsg.toString() +":" + apkPath);
        }else {
            Log.d("apk静默安装失败" ,errorMsg.toString() +":" + apkPath);
        }
        return result;
    }

    //静默卸载app
    @SuppressLint("MissingPermission")
    public static void uninstallApkAuto(String packageName) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent sender = PendingIntent.getActivity(NRTool.context(), 0, intent, 0);
        PackageInstaller mPackageInstaller = NRTool.context().getPackageManager().getPackageInstaller();
        mPackageInstaller.uninstall(packageName, sender.getIntentSender());// 卸载APK
    }

    //手动安装apk(安卓8.1安装测试OK)
    public static void installApk(String apkPath) {
        if(AppUtil.checkAppInstalled("com.sznaner.apkinstaller")){
            Intent intent = new Intent();
            //包名 包名+类名（全路径）
            intent.setClassName("com.sznaner.apkinstaller", "com.sznaner.apkinstaller.MainActivity");
            intent.putExtra("apkPath", apkPath);
            AppUtil.startActivity(intent);
        }else {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            File apkFile = (new File(apkPath));
            if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.N) {//>=安卓7.0
                StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                StrictMode.setVmPolicy(builder.build());
                builder.detectFileUriExposure();
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            intent.setDataAndType(Uri.fromFile(apkFile),"application/vnd.android.package-archive");
            NRTool.context().startActivity(intent);
        }
    }


    public interface InstallApkAutoCallBack {
        void finishCallBack(boolean result);
    }

}



